package com.ruoyi.system.controller;

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.quartz.task.RyTask;
import com.ruoyi.system.domain.MingChinaCity;
import com.ruoyi.system.domain.Mynews;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IMingChinaCityService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.tool.CommonWidth;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MingUserconfig;
import com.ruoyi.system.service.IMingUserconfigService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 用户信息配置Controller
 * 
 * @author ruoyi
 * @date 2023-03-03
 */
@RestController
@RequestMapping("/system/userconfig")
public class MingUserconfigController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(MingUserconfigController.class);
    @Autowired
    private IMingUserconfigService mingUserconfigService;

    @Autowired
    private IMingChinaCityService mingChinaCityService;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private ISysUserService userService;

    @PreAuthorize("@ss.hasPermi('system:userconfig:query')")
    @GetMapping(value = "/queryWeather")
    public AjaxResult getWeatherInfo()
    {
        String rtString = "";
        String areaCode = "101190101";
        SysUser user = SecurityUtils.getLoginUser().getUser();
        MingUserconfig mingUserconfig = mingUserconfigService.selectMingUserconfigById(user.getUserconfId());
        String brightness = "0";
        List<MingChinaCity> list = null;
        if (mingUserconfig!=null&&mingUserconfig.getWeather()!=null) {
            String[] area = mingUserconfig.getWeather().split(",");
            System.out.println("用户id："+user.getUserId());
            System.out.println("用户地址："+mingUserconfig.getWeather());
            MingChinaCity mingChinaCity = new MingChinaCity();
            mingChinaCity.setAdm1NameZh(area[0]);
            mingChinaCity.setAdm2NameZh(area[1]);
            rtString = area[1]+""+"\n";
            if (area.length==3) {
                String tmp = area[2];
                if (tmp.length()>2) {
                    tmp = tmp.substring(0,2)+"%";
                }
                mingChinaCity.setLocationNameZh(tmp);
                rtString = area[2]+""+"\n";
            }
            list = mingChinaCityService.selectMingChinaCityList(mingChinaCity);
            if (list!=null&&list.size()>=1) {
                areaCode = list.get(0).getLocationId()+"";
                System.out.println("用户地址编码："+areaCode);

            }
            brightness = mingUserconfig.getBrightness().toString();
        }

        log.info("获取天气预报信息:"+user.getUserName());
//要查询的地区编号


        if (RyTask.weatherMap.get(areaCode) == null) {
            //git clone https://github.com/qwd/LocationList.git
            //和风免费api，最多调用连续3天
            //String result = restTemplate.getForObject(
            //"https://devapi.qweather.com/v7/weather/3d?location=101190101&key=a36fae9e90b84c29b2b0b415779a8b72", String.class);

            //和风付费api，最大连续10天
//            String result = restTemplate.getForObject(
//                    "https://api.qweather.com/v7/weather/10d?location=101190101&key=3bec0920166d4b9383bdc5a8a29cb736", String.class);
            String result = restTemplate.getForObject(
                    "https://api.qweather.com/v7/weather/10d?location="+areaCode+"&key=3bec0920166d4b9383bdc5a8a29cb736", String.class);
            JSONObject param = JSONObject.parseObject(result);
            JSONArray json = JSONArray.parseArray(param.get("daily").toString());//JSONArray.fromObject(result); // 首先把字符串转成 JSONArray  对象
            if (json.size() > 0) {
                for (int i = 0; i < json.size(); i++) {
                    JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    rtString += (job.get("fxDate") + "-" + formatStr(job.get("textDay").toString()));  // 得到 每个对象中的属性值

                    if (job.get("tempMin").toString().length()==1) {
                        rtString += ("--(  " + job.get("tempMin") + "-");  // 得到 每个对象中的属性值
                    }
                    else {
                        rtString += ("--(" + job.get("tempMin") + "-");  // 得到 每个对象中的属性值
                    }
                    if (job.get("tempMax").toString().length()==1) {
                        rtString += "  "+(job.get("tempMax") + "度)--(");  // 得到 每个对象中的属性值
                    }
                    else {
                        rtString += (job.get("tempMax") + "度)--(");  // 得到 每个对象中的属性值
                    }
                    rtString += (job.get("windDirDay") + "");  // 得到 每个对象中的属性值
                    rtString += (job.get("windScaleDay") + "级)\n");  // 得到 每个对象中的属性值
                }

                rtString += "(QWeather)";
            }
        } else {
            rtString = RyTask.weatherMap.get(areaCode);
        }
        Mynews mynews = new Mynews();
        if (RyTask.weatherMap.get(areaCode)==null) {
            RyTask.weatherMap.put(areaCode, rtString);
        }

        mynews.setComment(rtString);
        if (StringUtils.isNotBlank(brightness)&&!"0".equals(brightness))
            mynews.setBrightness(brightness);

        if (mingUserconfig.getStartState()>0) {
            if (StringUtils.isNotBlank(mingUserconfig.getStopTime()) && judgeTime(mingUserconfig.getStopTime())) {
                mynews.setSleepTotalMinutes("" + calTotalMinutes(mingUserconfig.getStartTime()));
            }
        }

        AjaxResult ajax = AjaxResult.success();
        return AjaxResult.success(mynews);
    }

    public boolean judgeTime(String stopTime) {

        int givenHour = 12;
        int givenMinute = 30;
        if (StringUtils.isNotBlank(stopTime)) {
            String [] hms = stopTime.split(":");
            givenHour = Integer.parseInt(hms[0]);
            givenMinute = Integer.parseInt(hms[1]);
        }
        else {
            return false;
        }
        // 获取当前时间
        LocalTime currentTime = LocalTime.now();
        // 创建给定时间的 LocalTime 对象
        LocalTime givenTime = LocalTime.of(givenHour, givenMinute);
        // 计算当前时间与给定时间之间的分钟差
        long minutesDifference = ChronoUnit.MINUTES.between(currentTime, givenTime);
        log.info("给定时间在当前时间的 x 分钟范围以内:"+minutesDifference);
        // 判断给定时间是否在当前时间的 30 分钟范围以内
        if (Math.abs(minutesDifference) <= 30) {
            System.out.println("给定时间在当前时间的 30 分钟范围以内。");
            return true;
        }
        return false;
    }

    public long calTotalMinutes(String startTime ) {
        // 给定的小时和分钟字符串
        String hourString = "02";
        String minuteString = "30";

        if (StringUtils.isNotBlank(startTime)) {
            String [] hms = startTime.split(":");
            hourString = hms[0];
            minuteString = hms[1];
        }
        else
            return 0;

        // 将小时和分钟字符串转换为整数
        int hour = Integer.parseInt(hourString);
        int minute = Integer.parseInt(minuteString);

        // 计算总分钟数
        long totalMinutes = hour * 60 + minute;
        totalMinutes = 1000*60*totalMinutes;
        return totalMinutes;
    }


    public String formatStr (String value) {
        if (value.length()==1) {
            String rtVal = "  "+value+"  ";
//            "#ff0000 red#,#00ff00 green#,#0000ff blue#"
            if ("晴".endsWith(value)) {
                rtVal = "  #00ff00 "+value+"#  ";
            }
            return rtVal;
        }
        if (value.indexOf("雨")>=0) {
            value = "#ff0000 "+value+"#";
        }
        return value;
    }

    /**
     * 查询用户信息配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:userconfig:list')")
    @GetMapping("/list")
    public TableDataInfo list(MingUserconfig mingUserconfig)
    {
        startPage();
        List<MingUserconfig> list = mingUserconfigService.selectMingUserconfigList(mingUserconfig);
        return getDataTable(list);
    }

    /**
     * 导出用户信息配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:userconfig:export')")
    @Log(title = "用户信息配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MingUserconfig mingUserconfig)
    {
        List<MingUserconfig> list = mingUserconfigService.selectMingUserconfigList(mingUserconfig);
        ExcelUtil<MingUserconfig> util = new ExcelUtil<MingUserconfig>(MingUserconfig.class);
        util.exportExcel(response, list, "用户信息配置数据");
    }

    @PreAuthorize("@ss.hasPermi('system:userconfig:query')")
    @GetMapping("/query")
    public AjaxResult query()
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userConfId = user.getUserconfId();
        if (userConfId==null) {
            MingUserconfig mingUserconfigttt = mingUserconfigService.selectMingUserconfigByUId(user.getUserId());
            userConfId = mingUserconfigttt.getId();
        }

        MingUserconfig mingUserconfig = mingUserconfigService.selectMingUserconfigById(userConfId);
        return AjaxResult.success(mingUserconfig);
    }

    /**
     * 获取用户信息配置详细信息
     * 留言通知功能
     */
    @PreAuthorize("@ss.hasPermi('system:userconfig:query')")
    @GetMapping(value = "/queryNote")
    public AjaxResult queryNote()
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Mynews mynews = new Mynews();
        MingUserconfig mingUserconfig = mingUserconfigService.selectMingUserconfigById(user.getUserconfId());
        if (mingUserconfig!=null ) {
            String tmp =mingUserconfig.getNote();
            tmp = tmp.replaceAll("\r\n", "\n");
            tmp = tmp.replaceAll("\n", " ");
            System.out.println(tmp);
            int zimujiange_num = 46;
            if (mingUserconfig.getNote().length()>zimujiange_num) {
                mynews.setComment(CommonWidth.getStringW(tmp,zimujiange_num));
            }
            else {
                mynews.setComment(tmp);
            }
            log.info(mynews.getComment());
        } else {
            log.info("您赞无极简桌面配置信息！");
        }
        return AjaxResult.success(mynews);
    }

    @PreAuthorize("@ss.hasPermi('system:userconfig:query')")
    @GetMapping(value = "/queryNoteWX")
    public AjaxResult queryNoteWX()
    {
        AjaxResult ajax = AjaxResult.success();

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userConfId = user.getUserconfId();
        //xxx 此处为缓存的数据，不是数据库最新数据
        if (userConfId==null) {
            MingUserconfig mingUserconfigttt = mingUserconfigService.selectMingUserconfigByUId(user.getUserId());
            if (mingUserconfigttt!=null) {
                userConfId = mingUserconfigttt.getId();
            }
        }
//        SysUser newuser = userService.selectUserById(user.getUserId());
//        userConfId = newuser.getUserconfId();

        MingUserconfig mingUserconfig = mingUserconfigService.selectMingUserconfigById(userConfId);
//        Mynews mynews = new Mynews();
        if (mingUserconfig!=null) {
//            String tmp =mingUserconfig.getNote();
//            mynews.setComment(tmp);
//            log.info(mynews.getComment());
            return AjaxResult.success(mingUserconfig);
        } else {
//            mynews.setComment("未配置桌面留言信息");
            log.info("未配置桌面留言信息！");
            MingUserconfig mingUserconfigtmp = new MingUserconfig();
            mingUserconfigtmp.setUserId(user.getUserId());
            mingUserconfigtmp.setNote("未配置桌面留言信息！");
            mingUserconfigtmp.setSpeed(5);
            mingUserconfigtmp.setPeriod(1);
            mingUserconfigtmp.setNews("news,weather,stock,note");
            mingUserconfigtmp.setWeather("江苏省,南京市,鼓楼区");
            mingUserconfigtmp.setStock("600019.SH,600918.SH,000895.SZ,603636.SH");
            int rtv = mingUserconfigService.insertMingUserconfig(mingUserconfigtmp);
//            if ()
            MingUserconfig tmp = mingUserconfigService.selectMingUserconfigByUId(user.getUserId());
            SysUser usertmp = new SysUser();
            usertmp.setUserconfId((long)tmp.getId());
            usertmp.setUserId(user.getUserId());
            userService.updateUserStatus(usertmp);
            return AjaxResult.success(tmp);
//            mingUserconfigService.updateMingUserconfig();
        }

    }

    /*@PreAuthorize("@ss.hasPermi('system:userconfig:query')")
    @GetMapping(value = "/queryCfg")
    public AjaxResult queryCfg()
    {
        AjaxResult ajax = AjaxResult.success();
        Long userId = 54l;
        MingUserconfig mingUserconfig = new MingUserconfig();

        SysUser user = SecurityUtils.getLoginUser().getUser();
        userId = user.getUserId();

        mingUserconfig.setUserId(userId);
        MingUserconfig mynews = new MingUserconfig();
        List<MingUserconfig> userConf = mingUserconfigService.selectMingUserconfigList(mingUserconfig);
        if (userConf!=null && userConf.size() ==1) {
            MingUserconfig mingConf = userConf.get(0);
            String tmp =mingConf.getNote();
            tmp = tmp.replaceAll("\r\n", "\n");
            tmp = tmp.replaceAll("\n", " ");
            System.out.println(tmp);
            int zimujiange_num = 46;
            if (mingConf.getNote().length()>zimujiange_num) {
                mynews.setComment(CommonWidth.getStringW(tmp,zimujiange_num));
            }
            else {
                mynews.setComment(tmp);
            }
//            mynews.setComment(tmp);
            log.info(mynews.getComment());
        }
        return AjaxResult.success(mynews);
    }*/


    /**
     * 新增用户信息配置
     */
    @PreAuthorize("@ss.hasPermi('system:userconfig:add')")
    @Log(title = "用户信息配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MingUserconfig mingUserconfig)
    {
        return toAjax(mingUserconfigService.insertMingUserconfig(mingUserconfig));
    }

    /**
     * 修改用户信息配置 微信
     */
    @PreAuthorize("@ss.hasPermi('system:userconfig:edit')")
    @Log(title = "用户信息配置", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/updateNoteWX")
    public AjaxResult edit(@RequestBody MingUserconfig mingUserconfig)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userConfId = user.getUserconfId();
//        MingUserconfig tmp =  new MingUserconfig();
//        tmp.setId(userConfId);
//        tmp.setNote(mingUserconfig.getNote());
        if (userConfId==null) {
            MingUserconfig mingUserconfigttt = mingUserconfigService.selectMingUserconfigByUId(user.getUserId());
            userConfId = mingUserconfigttt.getId();
        }
        mingUserconfig.setId(userConfId);


        if ("".equals(mingUserconfig.getNews())&& StringUtils.isBlank(mingUserconfig.getStartTime())) {
            return AjaxResult.error();
        }
        return toAjax(mingUserconfigService.updateMingUserconfig(mingUserconfig));
    }

    /**
     * 删除用户信息配置
     */
    @PreAuthorize("@ss.hasPermi('system:userconfig:remove')")
    @Log(title = "用户信息配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mingUserconfigService.deleteMingUserconfigByIds(ids));
    }
}
